package site.wetsion.galio.auth.filter;

import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.web.filter.GenericFilterBean;
import sit.wetsion.galio.common.constant.AuthSecurityConstant;
import site.wetsion.galio.auth.support.RmsClientDetailsService;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Objects;

/**
 * 用于过滤用户登录及获取信息请求的filter
 *
 * @author weixin
 * @version 1.0
 * @CLassName UserFilter
 * @date 2019/5/15 7:47 PM
 */
public class UserFilter extends GenericFilterBean {

    private DataSource dataSource;

    public UserFilter(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        RmsClientDetailsService rmsClientDetailsService = new RmsClientDetailsService(dataSource);
        rmsClientDetailsService.setSelectClientDetailsSql(AuthSecurityConstant.DEFAULT_SELECT_STATEMENT);
        rmsClientDetailsService.setFindClientDetailsSql(AuthSecurityConstant.DEFAULT_FIND_STATEMENT);
        rmsClientDetailsService.setPasswordEncoder(NoOpPasswordEncoder.getInstance());

        String clientId = httpServletRequest.getHeader("clientId");
        String clientSecret = httpServletRequest.getHeader("clientSecret");

        try {
            ClientDetails clientDetails = rmsClientDetailsService.loadClientByClientId(clientId);
            if (Objects.isNull(clientDetails)) {
                httpServletResponse.sendError(401, "client not exist!");
            } else {
                if (!clientDetails.getClientSecret().equals(clientSecret)) {
                    httpServletResponse.sendError(401, "illegal client secret");
                }
            }
        } catch (NoSuchClientException nse) {
            httpServletResponse.sendError(401, "client not exist!");
        }
        chain.doFilter(request, response);
    }
}
